package com.longxiao.validator.handler;

import com.longxiao.validator.ValidException;
import com.longxiao.validator.ValidResult;
import com.longxiao.validator.handler.cond.CommCondition;
import com.longxiao.validator.handler.cond.StringCondition;

/**
 * Created by houhongwei on 2017/5/16.
 */
public class ValidStringHandler extends CommHandler implements ValidHandler {


    @Override
    public ValidResult validOther(Object value, CommCondition cond) throws ValidException {
        StringCondition strCond = null;
        if (cond instanceof StringCondition) {
            strCond = (StringCondition) cond;
        } else {
            return ValidResult.createSucc();
        }

        String tmp = getString(value);
        try {
            minLen(tmp, strCond);
            maxLen(tmp, strCond);
            ref(tmp, strCond);
            regex(tmp, strCond);
        } catch (ValidException e) {
            return ValidResult.createFail(e.getMsg());
        }
        return ValidResult.createSucc();
    }

    private String getString(Object value) {
        return (String) value;
    }

    private void minLen(String value, StringCondition strCond) throws ValidException {
        if (strCond.getMinLen() != null && value.length() < strCond.getMinLen()) {
            throw new ValidException(getErr(strCond));
        }
    }

    private void maxLen(String value, StringCondition strCond) throws ValidException {
        if (strCond.getMaxLen() != null && value.length() > strCond.getMaxLen()) {
            throw new ValidException(getErr(strCond));
        }
    }

    private void ref(String value, StringCondition strCond) throws ValidException {
        String[] ref = strCond.getRef();
        if (ref != null) {
            boolean bool = Boolean.FALSE;
            for (String s : ref) {
                if (s.equals(value)) {
                    bool = Boolean.TRUE;
                    break;
                }
            }
            if (bool == Boolean.FALSE) {
                throw new ValidException(getErr(strCond));
            }
        }
    }

    private void regex(String value, StringCondition strCond) throws ValidException {
        if (!value.matches(strCond.getRegex())) {
            throw new ValidException(getErr(strCond));
        }
    }
}
